package com.yuyou.fn.educational.service.impl;

import com.github.wens.mybatisplus.examples.Example;
import com.google.common.collect.Lists;
import com.mysql.jdbc.exceptions.MySQLIntegrityConstraintViolationException;
import com.yuyou.fn.common.exception.BusException;
import com.yuyou.fn.common.util.TimeUtils;
import com.yuyou.fn.educational.service.ICourseClassService;
import org.springframework.stereotype.Service;

import com.yuyou.fn.educational.mapper.DegreeLockRecordMapper;
import com.yuyou.fn.educational.entity.DegreeLockRecord;
import com.yuyou.fn.educational.service.IDegreeLockRecordService;
import com.github.wens.framework.service.impl.SuperServiceImpl;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.sql.SQLException;
import java.sql.Time;
import java.util.List;

/**
 *
 * DegreeLockRecord 表数据服务层接口实现类
 *
 */
@Service
public class DegreeLockRecordServiceImpl extends SuperServiceImpl<DegreeLockRecordMapper, DegreeLockRecord,Long> implements IDegreeLockRecordService {


    @Resource
    private ICourseClassService courseClassService ;


    @Transactional
    @Override
    public void lock(List<Long> classIds, Long stuId, String lockKey) {
        if(classIds.isEmpty()){
            return;
        }



        List<DegreeLockRecord> lockRecords = Lists.newArrayList() ;
        for(Long classId : classIds ){
            DegreeLockRecord degreeLockRecord = new DegreeLockRecord() ;
            degreeLockRecord.setClassId(classId);
            degreeLockRecord.setStudentId(stuId);
            degreeLockRecord.setLockKey(lockKey);
            degreeLockRecord.setCreateTime(TimeUtils.now());
            degreeLockRecord.setUpdateTime(TimeUtils.now());
            lockRecords.add(degreeLockRecord);
        }

        Example<DegreeLockRecord> countExample = DegreeLockRecord.createExample();
        countExample.createCriteria().andEqualTo("lockKey" , lockKey );
        if( countByExample(countExample) > 0 ){
            throw new BusException("重复锁定学位");
        }
        insertBatch(lockRecords);
        if( !courseClassService.increaseLockAmount(classIds) ){
            throw new BusException("学位数不够，锁学位失败");
        }
    }

    @Transactional
    @Override
    public void unlock(List<Long> classIds, Long stuId, String lockKey) {
        if(classIds.isEmpty()){
            return;
        }
        Example<DegreeLockRecord> example = DegreeLockRecord.createExample();
        example.createCriteria().andEqualTo("lockKey" , lockKey );
        boolean b = deleteByExample(example);
        if(b){
            courseClassService.decreaseLockAmount(classIds);
        }else{
            throw new BusException("解锁学位失败");
        }

    }
}